﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pub.Class;
using GTS.Channel.Api.Helper;
using GTS.Channel.Api.Entity;
using System.Web;
using System.Text.RegularExpressions;

namespace GTS.Channel.Api {
    /// <summary>
    /// 基本操作
    /// </summary>
    public static class Base {
        /// <summary>
        /// 域名
        /// </summary>
        public readonly static string DoMain = WebConfig.GetApp("DoMain");
        /// <summary>
        /// IP
        /// </summary>
        public readonly static string IP = WebConfig.GetApp("IP");
        /// <summary>
        /// 日志保存路径
        /// </summary>
        public readonly static string LogPath = WebConfig.GetApp("LogPath").GetMapPath();
        /// <summary>
        /// 是否启用日志
        /// </summary>
        public readonly static bool UseLog = WebConfig.GetApp("UseLog").ToBool();
        /// <summary>
        /// 是否启用日志
        /// </summary>
        public readonly static bool UseUrlLog = WebConfig.GetApp("UseUrlLog").ToBool();
        /// <summary>
        /// SmtpServer
        /// </summary>
        public readonly static string SmtpServer = WebConfig.GetApp("SmtpServer");
        /// <summary>
        /// SmtpPort
        /// </summary>
        public readonly static int SmtpPort = WebConfig.GetApp("SmtpPort").ToInt(25).IfLessThan(1, 25);
        /// <summary>
        /// SmtpUserName
        /// </summary>
        public readonly static string SmtpUserName = WebConfig.GetApp("SmtpUserName");
        /// <summary>
        /// SmtpPassword
        /// </summary>
        public readonly static string SmtpPassword = WebConfig.GetApp("SmtpPassword");
        /// <summary>
        /// FromEmail
        /// </summary>
        public readonly static string FromEmail = WebConfig.GetApp("FromEmail");
        /// <summary>
        /// SSL
        /// </summary>
        public readonly static bool IsSSL = WebConfig.GetApp("IsSSL").ToBool();
        /// <summary>
        /// 是否允许重复提交
        /// </summary>
        public readonly static bool UseRepeatSubmit = WebConfig.GetApp("UseRepeatSubmit").ToBool();
        /// <summary>
        /// 最后一次处理时间
        /// </summary>
        public static string LastDate = Log.ReadAll("~/config.ini".GetMapPath(), Encoding.UTF8).ReplaceRN().Trim();
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="msg">string</param>
        public static void WriteLog(string msg) {
            if (!UseLog) return;
            string LogFile = LogPath.TrimEnd('\\') + @"\Log_" + DateTime.Now.ToString("yyyyMMdd") + ".log";
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("/*******************************************************************************************************");
            sb.AppendLine(string.Format("* DateTime：{0}	", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            if (HttpContext.Current.IsNotNull()) {
                sb.AppendLine("* Url：" + Request2.GetUrl());
                sb.AppendLine("* Data：" + Request2.GetRequestInputStream());
                sb.AppendLine("* IP：" + Request2.GetIP());
            }
            sb.AppendLine("* Message：" + msg);
            sb.AppendLine("*******************************************************************************************************/");
            sb.AppendLine("");
            Log.Write(LogFile, sb.ToString());
        }
        /// <summary>
        /// 日志异常记录
        /// </summary>
        /// <param name="msg">异常</param>
        public static void WriteLog(Exception msg) {
            WriteLog(msg.ToExceptionDetail());
        }
        /// <summary>
        /// 写日志 输入消息 并结束
        /// </summary>
        /// <param name="msg">string</param>
        public static void WriteLogEnd(string msg) {
            WriteLog(msg);
            Msg.WriteEnd(msg);
        }
        /// <summary>
        /// 写日志URL
        /// </summary>
        /// <param name="url">string</param>
        public static void WriteLogUrl(string sp) {
            if (!UseUrlLog) return;
            string LogFile = LogPath.TrimEnd('\\') + "\\" + sp + @"\Log_" + DateTime.Now.ToString("yyyyMMdd") + ".log";
            StringBuilder sb = new StringBuilder();
            if (HttpContext.Current.IsNotNull()) sb.Append(Request2.GetUrl() + " " + Request2.GetRequestInputStream());
            try { Log.Write(LogFile, sb.ToString()); } catch (Exception ex) { Base.WriteLog(ex); }
        }
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="subject">主题</param>
        /// <param name="body">内容</param>
        /// <param name="to">发送给谁</param>
        /// <param name="useHtml">是否以HTML格式发送邮件</param>
        /// <returns></returns>
        public static bool SendEmail(string subject, string body, string to, bool useHtml = false) {
            return new Email()
                .Server(SmtpServer, SmtpPort)
                .To(t => t.Add(to))
                .Ssl(IsSSL)
                .Subject(subject)
                .Body(body)
                .Credentials(SmtpUserName, SmtpPassword)
                .From(FromEmail)
                .IsBodyHtml(useHtml)
                .Send();
        }
        /// <summary>
        /// 取SMS IVR的MO MT MR的接口
        /// </summary>
        /// <returns></returns>
        public static ISMSIVR ISMSIVR() {
            string url = Request2.GetUrl().ToLower();
            if (!UseRepeatSubmit) PostStack.RunContent(url);

            SPInfo spInfo = null;
            string sp = url.GetMatchingValues("http://(.+?)\\.{0}".FormatWith(Base.DoMain), "http://", "." + Base.DoMain).FirstOrDefault() ?? "";
            if (sp.IsNullEmpty()) {
                sp = url.GetMatchingValues("http://{0}:(\\d+)/".FormatWith(Base.IP), "http://{0}:".FormatWith(Base.IP), "/").FirstOrDefault() ?? "";
                if (sp.IsNullEmpty()) { Base.WriteLogEnd("参数错误!"); return null; }
                spInfo = SPInfoHelper.SelectListByAll("ConnString").Where(p => p.SPPort.Value == sp.ToInt(0)).FirstOrDefault().IfNull(new SPInfo());
                sp = spInfo.SPCode;
            } else {
                spInfo = SPInfoHelper.SelectListByAll("ConnString").Where(p => p.SPCode.ToLower() == sp).FirstOrDefault().IfNull(new SPInfo());
                sp = spInfo.SPCode;
            }
            if (sp.IsNullEmpty()) { Base.WriteLogEnd("不存在SP“{0}”!".FormatWith(sp)); return null; }
            if (!spInfo.Status.Value) { Base.WriteLogEnd("SP“{0}”已禁用!".FormatWith(sp)); return null; }

            ISMSIVR momt = (ISMSIVR)"GTS.Channel.Api.{0},GTS.Channel.Api".FormatWith(sp).LoadClass();
            return momt;
        }
        /// <summary>
        /// 从131上取通道数据
        /// </summary>
        /// <param name="spCode">SP代码</param>
        /// <param name="longPhone">长号码</param>
        /// <returns></returns>
        public static ChannelInfo GetChannelInfo(string spCode, string longPhone, string instruction = "") {
            string spName = SPInfoHelper.SelectListByAll("ConnString")
                .Where(p => p.SPCode == spCode)
                .FirstOrDefault()
                .SPDesc;
            IList<ChannelInfo> list = ChannelInfoHelper.SelectListByAll("MiniBox")
                .Where(p => (p.ChannelName.IndexOf(spName) != -1 || p.SPCode.ToLower() == spCode.ToLower()) && p.LongPhone.Trim().ToLower() == longPhone.ToLower())
                .ToList();
            if (!instruction.IsNullEmpty()) list = list.Where(p => p.Instruction.ToLower() == instruction.ToLower()).ToList();
            ChannelInfo extInfo = list.FirstOrDefault();
            return extInfo;
        }
        /// <summary>
        /// 从216上取IVR通道数据
        /// </summary>
        /// <param name="spCode">SP代码</param>
        /// <param name="longPhone">长号码</param>
        /// <returns></returns>
        public static IVRChannelInfo GetIVRChannelInfo(string spCode, string longPhone) {
            string spName = SPInfoHelper.SelectListByAll("ConnString")
                .Where(p => p.SPCode == spCode)
                .FirstOrDefault()
                .SPDesc;
            IList<IVRChannelInfo> list = IVRChannelInfoHelper.SelectListByAll("MiniBox");
            IVRChannelInfo extInfo = list
                .Where(p => (p.ChannelName.IndexOf(spName) != -1 || p.SPCode.ToLower() == spCode.ToLower()) && p.LongPhone.Trim().ToLower() == longPhone.ToLower())
                .FirstOrDefault();
            return extInfo;
        }
        /// <summary>
        /// 执行计划
        /// </summary>
        public static void RunJob() {
            //string lastdate = DateTime.Now.ToString("yyyyMMdd");
            //if (LastDate == lastdate) return;

            //string file = "~/config.ini".GetMapPath();
            //FileDirectory.FileDelete(file);
            //Log.Write(file, lastdate);
            //TasksTimer.RemoveAll();
            //TasksTimer.AddTask(new TaskInfo() {
            //    Assembly = "GTS.Channel.Api",
            //    Class = "GTS.Channel.Api.Job.ImportChannelIVRDealLog",
            //    Degree = 1,
            //    Interval = 1
            //});
            //LastDate = lastdate;
        }
        public static ChannelDealData GetInfo(ChannelDealData info) {
            //SHP2ACRI 112 C121E_KCD_E_32X16_QQV 30091 40566 405662532975680 JUL32012
            //          批次 设备号  游戏id plmn imsi 日期
            //SHBEUTY 112 6610_soC85H_soHX_soG004_soUI2 30061 405752 405752633054386
            string[] infos = null;
            string[] all = { "", "493", "GENERICDEVICE", "00999", "", "", "UnKnow" };
            if (info.ReceiveQuery.IndexOf(".") == -1) {
                infos = info.ReceiveQuery.Replace("  ", " ").Replace("+", " ").Split(' ');
                bool isBegin = false;
                int j = 1;
                for (int i = 0; i < infos.Length; i++) {
                    if (isBegin || infos[i].ToInt() > 0) {
                        isBegin = true;
                        all[j] = infos[i];
                        j++;
                        if (j > 6) break;
                    }
                }
            } else {
                infos = info.ReceiveQuery.Replace("  ", " ").Replace("+", " ").Split('.');
                for (int i = 0; i < infos.Length; i++) 
                    all[i] = infos[i];
                if (infos.Length == 2) {
                    infos = all[1].Replace("  ", " ").Replace("+", " ").Split(' ');
                    if (infos.Length > 1) {
                        for (int i = 0; i < infos.Length; i++)
                            all[i] = infos[i];
                    }
                }
            }
            info.MountCode = all[1].ToInt();
            info.DeviceCode = all[2].Replace("?", "_").Replace("", "_").Replace("?§", "_");
            info.DeviceCode = Regex.Replace(Regex.Replace(info.DeviceCode, @"[^[\w]", "_"), "(?s)([-])(?=.*\\1)", "_").ToUpper();
            info.GameCode = all[3].PadLeft(5, '0');
            info.PLMN = all[4].IsNullEmpty() ? info.PLMN : all[4];
            info.IMSI = info.IMSI.IsNullEmpty() ? all[5] : info.IMSI;
            info.ChargeCode = all[6].ToUpper();
            return info;
        }
    }
}
